document.addEventListener('DOMContentLoaded', function() {
  // 标签页切换功能
  const tabButtons = document.querySelectorAll('.tab-btn');
  const tabContents = document.querySelectorAll('.tab-content');

  tabButtons.forEach(button => {
    button.addEventListener('click', () => {
      const tabName = button.dataset.tab;
      
      tabButtons.forEach(btn => btn.classList.remove('active'));
      tabContents.forEach(content => content.classList.remove('active'));
      
      button.classList.add('active');
      document.getElementById(`${tabName}-tab`).classList.add('active');
    });
  });

  // OCR功能
  const dropZone = document.getElementById('dropZone');
  const imageInput = document.getElementById('imageInput');
  const imagePreview = document.getElementById('imagePreview');
  const ocrResult = document.getElementById('ocrResult');
  const copyResult = document.getElementById('copyResult');

  // 点击上传区域触发文件选择
  dropZone.addEventListener('click', () => imageInput.click());

  // 处理文件拖放
  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
  });

  dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
  });

  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    const file = e.dataTransfer.files[0];
    if (file && file.type.startsWith('image/')) {
      handleImage(file);
    }
  });

  imageInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
      handleImage(file);
    }
  });

  async function handleImage(file) {
    // 显示图片预览
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.innerHTML = `<img src="${e.target.result}" style="max-width: 100%; max-height: 200px;">`;
    };
    reader.readAsDataURL(file);

    // 执行OCR
    const formData = new FormData();
    formData.append('file', file);
    formData.append('apikey', 'YOUR_OCR_SPACE_API_KEY');
    formData.append('language', 'chs');

    try {
      ocrResult.innerHTML = '<div class="loading">正在识别中...</div>';
      const response = await fetch('https://api.ocr.space/parse/image', {
        method: 'POST',
        body: formData
      });

      const data = await response.json();
      console.log('ocrResult', data);
      if (data.ParsedResults?.length > 0) {
        ocrResult.textContent = data.ParsedResults[0].ParsedText;
      } else {
        ocrResult.innerHTML = '<div class="error">识别失败，请重试</div>';
      }
    } catch (error) {
      ocrResult.innerHTML = `<div class="error">错误：${error.message}</div>`;
    }
  }

  // 复制结果功能
  copyResult.addEventListener('click', () => {
    const text = ocrResult.textContent;
    navigator.clipboard.writeText(text).then(() => {
      copyResult.textContent = '已复制';
      setTimeout(() => {
        copyResult.textContent = '复制结果';
      }, 2000);
    });
  });

  // 运费查询功能
  const searchRates = document.getElementById('searchRates');
  const ratesResult = document.getElementById('ratesResult');

  searchRates.addEventListener('click', async () => {
    const origin = document.getElementById('origin').value;
    const destination = document.getElementById('destination').value;
    const weight = document.getElementById('weight').value;

    if (!origin || !destination || !weight) {
      alert('请填写完整信息');
      return;
    }

    try {
      ratesResult.innerHTML = '<div class="loading">正在查询...</div>';
      
      // 这里替换为实际的 Searates API 调用
      const response = await fetch('https://api.searates.com/freight/calculate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'YOUR_SEARATES_API_KEY'
        },
        body: JSON.stringify({
          origin,
          destination,
          weight: Number(weight)
        })
      });

      const data = await response.json();
      
      // 显示查询结果
      ratesResult.innerHTML = `
        <div class="rate-item">
          <h3>运费报价</h3>
          <p>起始港：${origin}</p>
          <p>目的港：${destination}</p>
          <p>预估费用：${data.amount} ${data.currency}</p>
          <p>预计时间：${data.transitTime} 天</p>
        </div>
      `;
    } catch (error) {
      ratesResult.innerHTML = `<div class="error">查询失败：${error.message}</div>`;
    }
  });

  // 汇率转换功能
  class ExchangeRateConverter {
    constructor() {
      console.log('ExchangeRateConverter');
      this.API_KEY = 'YOUR_API_KEY'; // 需要替换成你的 API key
      this.BASE_URL = 'https://api.exchangeratesapi.io/latest';
      
      this.amount = document.getElementById('amount');
      this.fromCurrency = document.getElementById('fromCurrency');
      this.toCurrency = document.getElementById('toCurrency');
      this.result = document.getElementById('result');
      
      this.initializeEventListeners();
    }

    initializeEventListeners() {
      [this.amount, this.fromCurrency, this.toCurrency].forEach(element => {
        element.addEventListener('change', () => this.convertCurrency());
      });
    }

    async convertCurrency() {
        console.log('convertCurrency');
        
      try {
        const amount = parseFloat(this.amount.value);
        const from = this.fromCurrency.value;
        const to = this.toCurrency.value;
        
        this.result.textContent = '正在获取汇率...';
        
        const response = await fetch(`${this.BASE_URL}${from}`);
        const data = await response.json();
        
        const rate = data.rates[to];
        const convertedAmount = (amount * rate).toFixed(2);
        
        this.result.textContent = `${amount} ${from} = ${convertedAmount} ${to}`;
      } catch (error) {
        this.result.textContent = '汇率获取失败，请稍后重试';
        console.error('汇率转换错误:', error);
      }
    }
  }

  // 初始化
  document.addEventListener('DOMContentLoaded', () => {
    const converter = new ExchangeRateConverter();
    converter.convertCurrency(); // 初始转换
  });
}); 